<?php

/**
 * Maikuro CMS
 *
 * LICENSE:
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * The license is bundled with this package in the file LICENSE.txt.
 * You may also obtain a copy of the License at this URL:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @copyright  Copyright (c) 2010, Jonathan Hedrén
 * @author     Jonathan Hedrén <jonathan.hedren@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 */

require_once 'Auth.php';
require_once 'BackendApplicationContext.php';
require_once 'CmsDependencyInjector.php';
require_once 'Constants.php';
require_once 'FrontController.php';
require_once 'FrontendApplicationContext.php';
require_once 'Session.php';
require_once 'Translator.php';
require_once 'backend/FormViewModel.php';
require_once 'backend/ViewModel.php';
require_once 'backend/Menu.php';
require_once 'backend/MenuItem.php';
require_once 'backend/AbstractBackendViewController.php';
require_once 'backend/AbstractBackendEntityViewController.php';
require_once 'cache/FileCacheHandler.php';
require_once 'db/MysqlPDO.php';
require_once 'event/EventHandler.php';
require_once 'event/IObserver.php';
require_once 'model/DefaultModelBinder.php';
//require_once 'plugin/AbstractPlugin.php';
require_once 'service/ServiceFactory.php';
require_once 'tag/ErrorTag.php';
require_once 'tag/PageTag.php';
require_once 'tag/SiteTag.php';
require_once 'tag/SnippetTag.php';

class MaikuroCms
{
    const VERSION = '0.1';

    private static $backendRunning = false;

    private static $frontendRunning = false;

    /**
     *
     * @return boolean
     */
    public static function isBackendRunning()
    {
        return self::$backendRunning;
    }

    /**
     *
     * @return boolean
     */
    public static function isFrontendRunning()
    {
        return self::$frontendRunning;
    }

    /**
     *
     * @param string $basePath
     */
    public static function runBackend($basePath)
    {
        self::$backendRunning = true;

        error_reporting(E_STRICT | E_ALL);

        $fc = FrontController::getInstance();

        $configFile = realpath($basePath . '/app/etc/config.php');
        if (!is_file($configFile)) {
            $fc->getRequest()->redirectTo('../setup/');
        }

        require_once $configFile;

        if (!isset($config)) {
            $fc->getRequest()->redirectTo('../setup/');
        }

        Session::start('maikurocms', 'fingerprint');

        $cacheHandler = new FileCacheHandler($basePath . '/app/cache/');

        $dbHandlerClass = $config['db']['handler'];
        $dbHandler = new $dbHandlerClass(
            $config['db']['user'],
            $config['db']['password'],
            $config['db']['database'],
            $config['db']['host']
        );

        $serviceFactory = new ServiceFactory($dbHandler, $cacheHandler, $basePath);

        $appContext = new BackendApplicationContext(
            $basePath,
            new EventHandler(),
            $fc->getRequest(),
            $fc->getResponse(),
            $serviceFactory
        );

        $adminSesLifetime = $serviceFactory->getSettingService()->getSettingValue('administratorSessionLifetime');
        Auth::setLifetime($adminSesLifetime);

        date_default_timezone_set($appContext->getCurrentSite()->timezone);

        //Translator::setTranslations(json_decode(file_get_contents('app/locale/sv_SE.json'), true));

        $fc->getView()
           ->setLayout('default');

        $fc->setDependencyInjector(new CmsDependencyInjector($appContext, $serviceFactory))
           ->throwExceptions(true);

//        $eventHandler = $appContext->getEventHandler();
//        $eventHandler->dispatchEvent(self::EVENT_PRE_DISPATCH, $fc);

        $fc->dispatch();

        Session::set(Constants::SESSION_PREVIOUS_REQUEST, $fc->getRequest());
    }

    /**
     *
     * @param string $basePath
     * @param string $siteCode
     */
    public static function runFrontend($basePath, $siteCode = 'default')
    {
        self::$frontendRunning = true;

        error_reporting(E_STRICT | E_ALL);

        $fc = FrontController::getInstance();

        $configFile = realpath($basePath . '/app/etc/config.php');

        if (!is_file($configFile)) {
            $fc->getRequest()->redirectTo('setup/');
        }

        require_once $configFile;

        if (!isset($config)) {
            $fc->getRequest()->redirectTo('setup/');
        }

        $dbHandlerClass = $config['db']['handler'];
        $dbHandler =  new $dbHandlerClass(
            $config['db']['user'],
            $config['db']['password'],
            $config['db']['database'],
            $config['db']['host']
        );


        Session::start('maikurocms', 'fingerprint');

        $cacheHandler = new FileCacheHandler($basePath . '/app/cache/');
        $serviceFactory = new ServiceFactory($dbHandler, $cacheHandler, $basePath);

        $appContext = new FrontendApplicationContext(
            $basePath,
            new EventHandler(),
            $fc->getRequest(),
            $fc->getResponse(),
            $serviceFactory
        );

        $currentSite = $serviceFactory->getSiteService()->getSite($siteCode);
        if ($currentSite == null) {
            throw new Exception('Unknown site.');
        }
        $appContext->setCurrentSite($currentSite);


        // TODO: Property på SiteEntity? + System setting för locale?
        // setlocale(LC_ALL, 'sv_SE');
        date_default_timezone_set($currentSite->timezone);

        $rewrites = array();
        $rewritesResult = $dbHandler->select('permalink', 'rewriteTo')
                                    ->from('rewrite')
                                    ->where('siteId = ?')
                                    ->bindValues($currentSite->id)
                                    ->fetchAll();

        foreach ($rewritesResult as $rewriteRule) {
            $rewrites[$rewriteRule->permalink] = $rewriteRule->rewriteTo;
        }
        $fc->setRewrites($rewrites);

        $dependencyInjector = new CmsDependencyInjector($appContext, $serviceFactory);

        $tagParser = $appContext->getTagParser();
        $tagParser->registerTag('error', $dependencyInjector->instanceWithDependencies('ErrorTag'))
                  ->registerTag('page', $dependencyInjector->instanceWithDependencies('PageTag'))
                  ->registerTag('site', $dependencyInjector->instanceWithDependencies('SiteTag'))
                  ->registerTag('snippet', $dependencyInjector->instanceWithDependencies('SnippetTag'));

        Autoloader::setBaseDir($basePath . '/');

        $fc->getView()->setBaseDir($basePath . '/');

        $fc->setDependencyInjector($dependencyInjector)
           ->dispatch();

        Session::set(Constants::SESSION_PREVIOUS_REQUEST, $fc->getRequest());
    }
}